package org.dromara.common.redis.handler

import org.dromara.common.core.utils.StringUtils
import org.redisson.api.NameMapper

/**
 * redis缓存key前缀处理
 *
 * @author LikeYouDo
 * @date 2025/7/13
 */

open class KeyPrefixHandler: NameMapper {
    val keyPrefix: String

    constructor(keyPrefix: String?) {
        // 前缀为空 则返回空前缀
        this.keyPrefix = if (StringUtils.isBlank(keyPrefix)) "" else "$keyPrefix:"
    }

    /**
     * 增加前缀
     */
    override fun map(name: String): String? {
        if (StringUtils.isBlank(name)) {
            return null
        }
        if (StringUtils.isNotBlank(keyPrefix) && !name.startsWith(keyPrefix)) {
            return keyPrefix + name
        }
        return name
    }

    /**
     * 去除前缀
     */
    override fun unmap(name: String): String? {
        if (StringUtils.isBlank(name)) {
            return null
        }
        if (StringUtils.isNotBlank(keyPrefix) && name.startsWith(keyPrefix)) {
            return name.substring(keyPrefix.length)
        }
        return name
    }
}
